<template>
  <div class="background">
    <div class="common-layout">
      <el-container>
        <el-header class="header_background">
          <div style="position: absolute; top: 0.1%; left: 2%;">
            <img alt="" src="@/assets/logo1.png" style="width: 40px;">
          </div>
          <div style="position: absolute; top: 1.5%; left: 38%;">
            <span style="font-size: 15px; font-weight: bold; color: whitesmoke">
              您好，用户&nbsp;&nbsp;{{ username }}&nbsp;&nbsp;！欢迎进入房屋租赁平台！
            </span>
          </div>
          <div class="right-info">
            <el-button @click="SignOut" style="margin-right: 10px;">
              <el-icon :size="18" style="margin-right: 5px;">
                <avatar />
              </el-icon>
              退出登录
            </el-button>
          </div>
        </el-header>
        <el-header class="sub_header_background">
          <el-menu
            :default-active="activeIndex"
            router
            class="el-menu-demo"
            mode="horizontal"
            background-color="#545c64"
            text-color="whitesmoke"
            active-text-color="white"
            style="height: 102%;"
            unique-opened
          >
            <el-menu-item index="/tenantHome">首页</el-menu-item>
            <el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
            <el-sub-menu index="transaction">
              <template #title>交易管理</template>
              <el-menu-item index="/TenantApplication">我的申请</el-menu-item>
              <el-menu-item index="/TenantRecord">交易记录</el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/SelectHouse">查看房源</el-menu-item>
            <el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
            <el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
            <el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
          </el-menu>
        </el-header>
        <el-main>
          <el-card id="personal-info-card" style="margin: 5px; min-height: calc(100vh - 110px);">
            <!-- 房源属性查询系统 -->
            <div class="graph-rag-container">
              <!-- 头部标题 -->
              <div class="header">
                <h1>房源属性查询系统</h1>
                <p>输入小区名称，可指定查询属性（如租金、户型），留空则返回全部属性</p>
              </div>

              <!-- 输入表单 -->
              <div class="form-group">
                <label for="community">小区名称 <span style="color:#d32f2f">*</span></label>
                <el-input 
                  type="text" 
                  id="community" 
                  v-model="community"
                  placeholder="例如：春申万科城"
                  @keypress.enter="handleCommunityEnter"
                ></el-input>
                <div class="form-hint">必填项，需准确输入小区名称关键词</div>
              </div>

              <div class="form-group">
                <label for="property">查询属性（可选）</label>
                <el-input 
                  type="text" 
                  id="property" 
                  v-model="property"
                  placeholder="例如：租金、户型、面积（留空返回全部属性）"
                  @keypress.enter="submitQuery"
                ></el-input>
                <div class="form-hint">支持同义词：如"价格"=租金、"楼层"=层高、"方向"=朝向</div>
              </div>

              <el-button class="btn-submit" @click="submitQuery" :loading="loading">
                查询小区属性
              </el-button>

              <!-- 加载状态 -->
              <div class="loading" v-if="loading">
                <div class="spinner"></div>
                <p>正在查询，请稍候...</p>
              </div>

              <!-- 错误提示 -->
              <el-alert
                v-if="error"
                :title="error"
                type="error"
                show-icon
                class="error-alert"
              ></el-alert>

              <!-- 结果展示 -->
              <div class="result" v-if="resultData">
                <div class="result-header">
                  <div class="result-title">查询结果：{{ resultData.community }}</div>
                  <div class="result-subtitle">查询属性：{{ resultData.property }}</div>
                </div>
                <div class="result-content">{{ resultData.answer }}</div>
                <div class="result-sources" v-if="resultData.sources && resultData.sources.length > 0">
                  <div class="sources-title">参考信息</div>
                  <div v-for="(src, index) in resultData.sources" :key="index" class="source-item">
                    {{ src }}
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import request from "@/axios/request";
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      loading: false,
      tenantId: '',
      username: '',
      password: '',
      phone: '',
      email: '',
      activeIndex: '/PersonalAssistant',
      
      // GraphRAG 相关数据
      community: '',
      property: '',
      error: '',
      resultData: null
    };
  },
  mounted() {
    this.fetchUserInfo();
  },
  methods: {
    async fetchUserInfo() {
      let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
      if (token && token.tenantId) {
        const tenantId = token.tenantId;
        const res = await request.get(`/tenant/findById/${tenantId}`);
        if (res.code === 200) {
          token = res.data;
        } else {
          ElMessage.error("获取用户信息失败");
        }
        console.log(token);
        if (!token) {
          ElMessage.error("获取用户信息失败");
          console.log("获取用户信息失败");
          return;
        }
        this.tenantId = token.tenantId;
        this.username = token.username;
        this.password = token.password;
        this.phone = token.phone;
        this.email = token.email;
      }
    },
    
    SignOut() {
      sessionStorage.clear();
      ElMessage({
        message: '用户退出登录',
        type: 'success',
      });
      this.$router.replace({ path: '/Login' });
    },

    // 处理小区名称输入框的Enter键
    handleCommunityEnter() {
      document.getElementById("property").focus();
    },

    // 提交查询函数
    async submitQuery() {
      // 1. 输入验证
      if (!this.community) {
        this.error = "请输入小区名称（必填项）";
        this.resultData = null;
        return;
      }
      this.error = ''; // 清除之前的错误提示

      // 2. 显示加载状态
      this.loading = true;
      this.resultData = null;

      try {
        // 3. 发送请求到后端
        const response = await fetch("http://localhost:8085/rag/query", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            community: this.community,
            question: this.property
          })
        });

        // 4. 处理响应
        if (!response.ok) {
          throw new Error(`请求失败（${response.status}）：${response.statusText}`);
        }
        const data = await response.json();

        // 5. 展示结果
        if (data.code === 200) {
          this.resultData = data.data;
        } else {
          this.error = `查询失败：${data.msg}`;
        }

      } catch (err) {
        // 6. 处理异常
        this.error = `系统错误：${err.message}（请检查后端服务是否启动）`;
      } finally {
        // 7. 隐藏加载状态
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.background {
  background-color: whitesmoke;
  height: 100vh;
}

.header_background {
  background-color: #1b4989;
  height: 6vh;
}

.sub_header_background {
  background-color: #545c64;
  height: 7vh;
}

.right-info {
  width: 100px;
  position: absolute;
  right: 2%;
  top: 0.7%
}

.right-info:hover {
  cursor: pointer;
}

.el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
  border-color: #409EFF;
}

.line { 
  background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x; 
  height: 0.4rem; 
  flex: 1; 
  background-size: auto;
  margin: 0.16rem;
}

/* GraphRAG 样式 */
.graph-rag-container {
  max-width: 700px;
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.05);
}

.graph-rag-container .header {
  text-align: center;
  margin-bottom: 30px;
}

.graph-rag-container .header h1 {
  color: #1a73e8;
  font-size: 24px;
  margin-bottom: 8px;
}

.graph-rag-container .header p {
  color: #666;
  font-size: 14px;
}

.graph-rag-container .form-group {
  margin-bottom: 22px;
}

.graph-rag-container .form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  font-size: 15px;
}

.graph-rag-container .form-hint {
  margin-top: 6px;
  color: #888;
  font-size: 13px;
}

.graph-rag-container .btn-submit {
  width: 100%;
  padding: 14px;
  background-color: #1a73e8;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.graph-rag-container .btn-submit:hover {
  background-color: #1557b0;
}

.graph-rag-container .loading {
  text-align: center;
  padding: 30px 0;
}

.graph-rag-container .loading .spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(26, 115, 232, 0.2);
  border-top-color: #1a73e8;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.graph-rag-container .loading p {
  color: #666;
  font-size: 15px;
}

.graph-rag-container .result {
  margin-top: 30px;
  padding: 24px;
  border-radius: 8px;
  background-color: #f8fafc;
  border: 1px solid #e2e8f0;
}

.graph-rag-container .result-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.graph-rag-container .result-title {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-bottom: 4px;
}

.graph-rag-container .result-subtitle {
  font-size: 13px;
  color: #666;
}

.graph-rag-container .result-content {
  font-size: 15px;
  color: #333;
  line-height: 1.6;
  white-space: pre-line;
}

.graph-rag-container .result-sources {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px dashed #e2e8f0;
}

.graph-rag-container .sources-title {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  margin-bottom: 8px;
}

.graph-rag-container .source-item {
  font-size: 13px;
  color: #888;
  margin-bottom: 4px;
  padding-left: 12px;
  position: relative;
}

.graph-rag-container .source-item::before {
  content: "•";
  position: absolute;
  left: 0;
  color: #bbb;
}

.graph-rag-container .error-alert {
  margin-top: 30px;
}
</style>